package com.lwg.practice.java8.behaviparam;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.function.Predicate;

/**
 * @FileName: FilterApples.java
 * @Description: 行为参数化
 * Copyright: Copyright(C) 2020-2022
 * Company  : Sunyard.hangzhou
 * @author: 李炜光
 * @slogan:
 * @Date: 2021/12/21 0021
 */
public class FilterApples {


    // 行为参数化：让filterApples方法接收ApplePredicate对象，对Apple进行条件测试。
    // 即让方法接收多种行为(对象)作为参数,并在内部使用，来完成不同的行为。
    public interface ApplePredicate {
        boolean filter(Apple apple);
    }

    public static class AppleGreenColerPredicate implements ApplePredicate {
        @Override
        public boolean filter(Apple apple) {
            return "green".equals(apple.getColor()) && apple.getWeight() > 150;
        }
    }

    public static List<Apple> filterApples(List<Apple> apples,ApplePredicate applePredicate){
        List<Apple> result=new ArrayList<>();
        for (Apple apple : apples) {
            if (applePredicate.filter(apple)){
                result.add(apple);
            }
        }
        return result;
    }

    public static void main(String[] args) {
        List<Apple> appleList = Arrays.asList(new Apple(80,"green"),
                new Apple(155, "green"), new Apple(120, "red"));
        //List<Apple> apples = filterApples(appleList, new AppleGreenColerPredicate());
        List<Apple> apples = filterApples(appleList, (Apple apple) -> "green".equals(apple.getColor()) && apple.getWeight() > 150);
        System.out.println(apples);
    }

    public static class Apple {
        private int weight = 0;
        private String color = "";

        public Apple(int weight, String color) {
            this.weight = weight;
            this.color = color;
        }

        public Integer getWeight() {
            return weight;
        }

        public void setWeight(Integer weight) {
            this.weight = weight;
        }

        public String getColor() {
            return color;
        }

        public void setColor(String color) {
            this.color = color;
        }

        public String toString() {
            return "Apple{" +
                    "color='" + color + '\'' +
                    ", weight=" + weight +
                    '}';
        }
    }

}